home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: netcom.com!marnold
- From: marnold@netcom.com (Matt Arnold)
- Subject: Re: Boolean evaluation operator
- Message-ID: <marnoldDo1CsK.2rK@netcom.com>
- Organization: NETCOM On-line Communication Services (408 261-4700 guest)
- References: <4hqcnk$aoj@natasha.rmii.com> <4hte6e$55k@park.interport.net>
- Date: Sun, 10 Mar 1996 05:05:08 GMT
- Sender: marnold@netcom3.netcom.com
-
- yaron@interport.net (Adi) writes:
-
- >disch@aartronics.com wrote:
-
- >>We have a Boolean class that contains the following operator:
-
- >> // Returns 1 if THIS Boolean Object is false, and 0 if THIS Boolean Object
- >> // is true.
- >> int
- >> Boolean::operator!(); // No referenced object; operates on THIS
-
- >>When used in the following code fragment, compilation fails with the message
- >>"Error testbed.cpp 47: Illegal structure operation in function main()":
-
- >> Boolean bTrue = T;
- >> Boolean bFalse = F;
- >> if (!bFalse)
- >> {
- >> cout << "bFalse" << endl;
- >> }
- >> if (bTrue)
- >> {
- >> cout << "bTrue" << endl;
- >> }
-
- >>Is there a way to define an evaluation operator so that "if (bTrue)" will
- >>compile and execute as expected?
-
- >>Any input would be greatly appreciated.
-
- >>Bob Dischner
- >>Aartronics Corp
-
- First, a question. Why this whole compilcated Boolean class anyway? What's
- wrong with the built-in bool type (if you compiler supports it), or the
- following temporary emulation until it does...
-
- #define bool int
- #define true 1
- #define false 0
-
- ...??
-
- >Try something like this :
-
-
- >class Boolean {
- > public :
- > Boolean(unsigned int b = FALSE)
- > : value(b) {}
-
- > Boolean(const Boolean& b)
- > : value(b.value) {}
-
- > virtual ~Boolean() {}
-
- > operator unsigned int()
- > {
- > return value;
- > }
-
- > Boolean& operator !()
- > {
- > value = !value; return *this;
- > }
-
- Shouldn't this be...
-
- Boolean operator !()
- {
- Boolean not_value(!value);
-
- return not_value;
- }
-
-
- You certinaly don't want operator!() to change the value of the Boolean
- object it's called for! It should instead return a new Boolean which has
- the opposite state. With the orignal definiation of opeator!() by Adi,
- the statement...
-
- if (!bFalse)
- // ...
-
- ...would certinaly branch correctly (the first time), but bFalse would
- continue to be true afterwards, since it's state was changed. This would
- be incorrect. My definition of operator!() is the correct one.
-
- This is similar to what is done with operator+(); it doesn't modify (add
- to) the object it's called for, it instead returns a new object, equal to
- the current object plus the other operand.
-
- > Boolean& operator = (const Boolean& t)
- > {
- > value = t.value;
- > return *this;
- > )
-
- > protected :
- > unsigned int value;
- >};
-
-
-
- >NOTE :
-
- >The important thing here is the cast operator to unsigned integer.
-
-
-
- >Adi Degani
- >New-York, NY
-
-
-